<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div class="sign-detail-container no-margin mobile-radius">
      <template v-if="!permissionDenied">
        <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" :is-expedited="detailInfo.isExpedited"/>
        <explanation :explanation="explanationObj" :countdown="true" @queryProcessData="queryProcessData" />
        <div v-loading="infoLoading" class="sign-detail-content small-padding">
          <el-image v-if="isRevoke" :src="revokeImg" class="revoke-img"/>
          <div style="margin-bottom: 32px;">
            <Title title="申请信息" style="margin:0px 0 10px 0;"/>
            <BaseInfo ref="baseInfo" :base-info="detailInfo" :is-examine="isExamine" :is-current-version="isCurrentVersion" :id="Number(id)" @freshDetail="queryInfo"/>
          </div>
        </div>
        <ExamineAndApprove
          ref="examineAndApproveRef"
          :disabled="infoLoading"
          :process-id="processId"
          :main-id="id"
          :version="version"
          :get-comments-api="externalHarvestComments"
          :comment-add-api="externalHarvestCommentAdd"
          :process-revocation-api="externalHarvestProcessRevocation"
          :process-recall-api="externalHarvestProcessRecall"
          :process-audit-api="externalHarvestProcessAudit"
          :create-user="createUser"
          :business-type="BUSINESS_TYPE.EXTERNALHARVEST"
          :process-type="PROCESS_TYPE.EXTERNALHARVEST"
          :audit-schedule-data="auditScheduleData"
          :senders="senders"
          :default-auth-user-list="[authUser]"
          :default-aduitor-list="[{id: detailInfo.proposer, userName: detailInfo.proposerName}]"
          :approval-module-type="APPROVAL_MODULE_TYPE.EXTERNALHARVEST"
          :show-print="true"
          :print-data="detailInfo"
          :is-apply="isApply"
          redirect-url="/orderPage/externalHarvestDetail"
          detail-page-router-name="externalHarvestDetail"
          edit-page-router-name="externalHarvestEdit"
          @toBack="toBack"
          @setProcessData="setProcessData"
          @handlePressSend="handlePressSend"
          @getAuditSchedule="getAuditSchedule"
          @queryProcessData="queryProcessData"
          @handleCreateNew="handleCreateNew"
          @handleSendMsg="handleSendMsg"
          @handleSender="handleSender"
          @handleModify="handleModify('externalHarvestEdit',{id: id},{remodifyId: processId})"
          @getHistoryDetail="getHistoryDetail"
          @setCurrentVersion="setCurrentVersion"
          @freshDetail="queryInfo"
          @handleCancelPress="handleCancelPress"
        />
        <ding-ding-dialog
          ref="pressSendDialogRef"
          :btn1="'确认加急'"
          :btn2="'取消'"
          :show-send-checkbox="false"
          :select-with-user-load="false"
          :default-list="pressDefaultList"
          redirect-url="/orderPage/externalHarvestDetail"
          summary-title="加急原因"
          title="催办通知"
          @handelOK="toSend" />
      </template>
      <DeniedPlaceholder v-else />
    </div>
  </div>
</template>
<script>
// 组件
import ListTab from '@/components/ListTab';
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import Title from '@/components/Title';
import explanation from '@/components/Common/explanation';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';
import BaseInfo from './components/baseInfo';

// 工具函数
import { mapState } from 'vuex';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { APPROVAL_MODULE_TYPE } from '@/utils/const';
import { hasRouteAuth } from '@/utils/permission';
import { BUSINESS_TYPE, PROCESS_TYPE, EVENT_TYPE } from '@/utils/const/process';

// API
import {
  externalHarvestInfo, externalHarvestCommentAdd, externalHarvestProcessRecall,
  externalHarvestComments, externalHarvestProcessRevocation, externalHarvestProcessAudit
} from '@/api/externalHarvest';
import schedule from '@/mixins/schedule';
import revokeImg from '@/assets/auditProcess/process_status_3.png';

export default {
  components: {
    ListTab, ProgressStep, Title,
    explanation, ExamineAndApprove, BaseInfo
  },
  mixins: [schedule],
  data() {
    return {
      APPROVAL_MODULE_TYPE, EVENT_TYPE,
      externalHarvestCommentAdd, externalHarvestProcessRecall,
      externalHarvestComments, externalHarvestProcessRevocation, externalHarvestProcessAudit,
      revokeImg,
      BUSINESS_TYPE, PROCESS_TYPE,
      id: '', // 还款单id
      processId: '', // 流程id
      detailInfo: {},
      infoLoading: false,
      permissionDenied: false, // 详情页是否可查看
      PROGRESS_STEP,
      // api
      stepActiveId: PROGRESS_STEP.PENDING,
      isRevoke: false,
      processData: {
        list: []
      }
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    },
    createUser() {
      let user = { id: this.detailInfo.creatorId, userName: this.detailInfo.creator };
      if (this.userInfo.id === this.detailInfo.creatorId) {
        user = this.userInfo;
      }
      return user;
    },
    authUser() {
      return { id: this.detailInfo.authUserId, userName: this.detailInfo.authUser };
    },
    isExamine() { // 当前用户是否是当前节点审批人
      const processList = this.processData.list;
      if (!processList || processList.length === 0) return false;
      let item = null;
      processList.forEach(i => {
        // nodeStatus 节点状态： 0：结束 1：进行中 2：未审批
        if (!item && i.nodeStatus === 1) {
          item = i;
        }
      });
      if (!item || item.length === 0) return false;
      let userList = [];
      item.items.forEach(i => {
        userList = userList.concat(i.users);
      });
      return userList.some(i => {
        return i.id === this.userInfo.id;
      });
    },
    isApply() { // 申请人
      const proposer = this.detailInfo && this.detailInfo.proposer ? this.detailInfo.proposer : '';
      return proposer && this.userInfo.id === proposer;
    },
    events() {
      return this.processData.operation && this.processData.operation.setEvents ? this.processData.operation.setEvents : [];
    }
  },
  created() {
    this.initData();
  },
  mounted() {
    if (this.$route.query.openComment) {
      this.$refs.examineAndApproveRef.isShowProcess = true;
    }
  },
  methods: {
    hasRouteAuth,
    initData() {
      this.initRouteData();
      this.queryProcessData(); // 流程数据
    },
    initRouteData() {
      this.id = this.$route.query.id;
      this.processId = this.$route.query.processId;
      if (!this.id || !this.processId) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    setProcessData(processData) {
      this.processData = processData;
    },
    // 获取基本信息
    queryInfo() {
      this.infoLoading = true;
      externalHarvestInfo(this.id).then(res => {
        this.handleProcessCheck(res.data.processId);
        this.handleDetailData(res);
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.infoLoading = false;
      });
    },
    // 处理详情接口返回的数据
    handleDetailData(res) {
      this.infoLoading = false;
      if (res.code === 200) {
        this.commentCount = res.data.commentCount;
        if (res.data.processStatus === 3) { // 3为撤销
          this.stepActiveId = PROGRESS_STEP.PENDING;
          this.isRevoke = true;
        } else {
          this.stepActiveId = res.data.processStatus;
          this.isRevoke = false;
        }
        this.detailInfo = res.data;
      }
    },
    queryProcessData() {
      this.queryInfo();
      this.getAuditSchedule();
      this.$nextTick(() => {
        this.$refs.examineAndApproveRef && this.$refs.examineAndApproveRef.getProcessList();
      });
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'externalHarvest' });
      }
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    handleCreateNew() {
      const routeUrl = this.$router.resolve({
        name: 'externalHarvestEdit',
        params: { id: this.id },
        query: { reapplyId: this.processId, createNew: 1 }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
	.sign-detail-container{
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding-bottom: 55px;
    min-height: calc(100vh - 64px);
		.sign-detail-content{
      position: relative;
			padding: 16px 24px 56px;
		}
    &::v-deep {
      .explanation-container{
        .explanation{
          padding-left: 32px!important;
        }
      }
    }
    .revoke-img{
      position: absolute;
      width: 80px;
      height: 80px;
      right: 56px;
      top: 33px;
      z-index: 999;
    }
    .list-tab{
      padding: 0 0 0 10px !important;
      &::v-deep {
        .item-content{
          padding: 16px 0 8px 0 !important;
        }
      }
    }
    .account-header{
      display: flex;
      margin: 32px 0 16px;
      .title-tip{
        font-weight: normal;
        color: #999;
        font-size: 14px;
        margin: 0 4px 0 6px;
      }
      &::v-deep {
        .el-radio{
          display: flex;
          align-items: center;
        }
        .el-radio__label{
          color: #333333;
          padding-left: 4px;
        }
      }
    }
    .empty-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-top: 30px;
      .text {
        font-size: 14px;
        font-weight: 400;
        text-align: left;
        color: #999999;
        line-height: 20px;
        margin-top: 10px;
      }
      .blue {
        color: #406ef4;
      }
      img {
        width: 120px;
      }
    }
	}
  .list-tab{
    padding: 0 !important;
  }
		::v-deep .el-form-item__label {
			color: #999;
		}
		::v-deep .el-form-item {
			margin-bottom: 0 !important;
		}
		::v-deep .explanation {
			margin-bottom: 0;
		}
</style>
